<?php
namespace app\api\controller;

use think\Controller;
use think\Request;
use app\admin\model\scanwork\Config as ConfigModel;

class Bg extends Controller
{
    // 用户绑定 fastadmin 账户
    public function bindUser(Request $request)
    {
        $openid = $request->post('openid');
        $username = $request->post('username');
        $password = $request->post('password');
        if (!$openid || !$username || !$password) {
            return json(['code' => 0, 'msg' => '参数缺失']);
        }
        $user = db('user')->where('username', $username)->find();
        // 修正密码校验方式，兼容fastadmin
        if (!$user || md5(md5($password) . $user['salt']) !== $user['password']) {
            return json(['code' => 0, 'msg' => '用户名或密码错误']);
        }
        // 绑定 openid
        db('user')->where('id', $user['id'])->update(['openid' => $openid]);
        return json(['code' => 1, 'msg' => '绑定成功', 'data' => ['user_id' => $user['id']]]);
    }

    // 报工提交
    public function submitWork(Request $request)
    {
        $openid = $request->post('openid');
        $work_data = $request->post('work_data');
        $user = db('user')->where('openid', $openid)->find();
        if (!$user) {
            return json(['code' => 0, 'msg' => '未绑定用户']);
        }
        // 假设 work_data 包含工种、工时、日期等
        $data = [
            'user_id' => $user['id'],
            'work_type' => $work_data['work_type'] ?? '',
            'work_time' => $work_data['work_time'] ?? 0,
            'work_date' => $work_data['work_date'] ?? date('Y-m-d'),
            'remark' => $work_data['remark'] ?? '',
            'createtime' => time()
        ];
        db('work_report')->insert($data);
        return json(['code' => 1, 'msg' => '报工提交成功']);
    }

    // 报工查看
    public function viewWork(Request $request)
    {
        $openid = $request->get('openid');
        $user = db('user')->where('openid', $openid)->find();
        if (!$user) {
            return json(['code' => 0, 'msg' => '未绑定用户']);
        }
        $list = db('work_report')->where('user_id', $user['id'])->order('work_date desc')->select();
        return json(['code' => 1, 'msg' => '报工信息', 'data' => $list]);
    }

    // 工资查询
    public function viewSalary(Request $request)
    {
        $openid = $request->get('openid');
        $user = db('user')->where('openid', $openid)->find();
        if (!$user) {
            return json(['code' => 0, 'msg' => '未绑定用户']);
        }
        $month = date('Y-m');
        $startTime = strtotime($month . '-01 00:00:00');
        $endTime = strtotime($month . '-' . date('t', $startTime) . ' 23:59:59');
        $wages = db('scanwork_report')
            ->where('user_id', $user['id'])
            ->where('status', 1)
            ->where('createtime', 'between', [$startTime, $endTime])
            ->order('createtime desc')
            ->select();
        $totalWage = array_sum(array_column($wages, 'wage'));
        return json(['code' => 1, 'msg' => '工资信息', 'data' => [
            'wages' => $wages,
            'totalWage' => $totalWage,
            'month' => $month
        ]]);
    }

    // 获取任务列表
    public function tasks(Request $request)
    {
        $openid = $request->get('openid');
        $user = db('user')->where('openid', $openid)->find();
        if (!$user) {
            return json(['code' => 0, 'msg' => '未绑定用户']);
        }
        $tasks = db('scanwork_allocation')
            ->alias('a')
            ->join('scanwork_order o', 'a.order_id = o.id')
            ->join('scanwork_model m', 'a.model_id = m.id')
            ->join('scanwork_product p', 'm.product_id = p.id')
            ->join('scanwork_process pr', 'a.process_id = pr.id')
            ->where('a.user_id', $user['id'])
            ->where('a.status', 0)
            ->field('a.*, o.order_no, p.name as product_name, m.name as model_name, pr.name as process_name')
            ->order('a.createtime desc')
            ->select();
        return json(['code' => 1, 'msg' => '获取成功', 'data' => $tasks]);
    }

    // 获取任务详情
    public function report(Request $request)
    {
        $openid = $request->get('openid');
        $allocationId = $request->get('id');
        $user = db('user')->where('openid', $openid)->find();
        if (!$user) {
            return json(['code' => 0, 'msg' => '未绑定用户']);
        }
        if (!$allocationId) {
            return json(['code' => 0, 'msg' => '未指定任务ID']);
        }
        $allocation = db('scanwork_allocation')
            ->alias('a')
            ->join('scanwork_order o', 'a.order_id = o.id')
            ->join('scanwork_model m', 'a.model_id = m.id')
            ->join('scanwork_product p', 'm.product_id = p.id')
            ->join('scanwork_process pr', 'a.process_id = pr.id')
            ->where('a.id', $allocationId)
            ->where('a.user_id', $user['id'])
            ->field('a.*, o.order_no, p.name as product_name, m.name as model_name, pr.name as process_name')
            ->find();
        if (!$allocation) {
            return json(['code' => 0, 'msg' => '任务不存在或不属于当前用户']);
        }
        return json(['code' => 1, 'msg' => '获取成功', 'data' => $allocation]);
    }

    // 提交报工
    public function submit(Request $request)
    {
        $openid = $request->post('openid');
        $allocationId = $request->post('allocation_id');
        $quantity = $request->post('quantity');
        $remark = $request->post('remark');
        $user = db('user')->where('openid', $openid)->find();
        if (!$user) {
            return json(['code' => 0, 'msg' => '未绑定用户']);
        }
        if (!$allocationId || !$quantity) {
            return json(['code' => 0, 'msg' => '参数不完整']);
        }
        $allocation = db('scanwork_allocation')->where('id', $allocationId)->where('user_id', $user['id'])->find();
        if (!$allocation) {
            return json(['code' => 0, 'msg' => '任务不存在或不属于当前用户']);
        }
        if ($allocation['status'] != 0) {
            return json(['code' => 0, 'msg' => '任务已完成，无法重复报工']);
        }
        $processPrice = db('scanwork_process_price')
            ->where('model_id', $allocation['model_id'])
            ->where('process_id', $allocation['process_id'])
            ->find();
        if (!$processPrice) {
            return json(['code' => 0, 'msg' => '工序工价记录未找到']);
        }
        $wage = $quantity * $processPrice['price'];
        $reportData = [
            'allocation_id' => $allocationId,
            'user_id' => $user['id'],
            'quantity' => $quantity,
            'wage' => $wage,
            'remark' => $remark,
            'status' => 0,
            'createtime' => time()
        ];
        $reportId = db('scanwork_report')->insertGetId($reportData);
        if (!$reportId) {
            return json(['code' => 0, 'msg' => '报工失败']);
        }
        db('scanwork_allocation')->where('id', $allocationId)->update(['status' => 1]);
        return json(['code' => 1, 'msg' => '报工成功', 'data' => ['report_id' => $reportId]]);
    }

    // 上传报工图片
    public function uploadImage(Request $request)
    {
        $openid = $request->post('openid');
        $reportId = $request->post('report_id');
        $user = db('user')->where('openid', $openid)->find();
        if (!$user) {
            return json(['code' => 0, 'msg' => '未绑定用户']);
        }
        if (!$reportId) {
            return json(['code' => 0, 'msg' => '缺少报工ID']);
        }
        if (!empty($_FILES['file'])) {
            $file = $_FILES['file'];
            if ($file['error'] == 0) {
                $ext = pathinfo($file['name'], PATHINFO_EXTENSION);
                $filename = date('YmdHis') . '_' . substr(md5(uniqid()), 0, 8) . '.' . $ext;
                $dateDir = date('Y-m-d');
                $uploadDir = 'uploads/baogong/' . $dateDir . '/';
                if (!is_dir($uploadDir)) {
                    mkdir($uploadDir, 0755, true);
                }
                $filepath = $uploadDir . $filename;
                if (move_uploaded_file($file['tmp_name'], $filepath)) {
                    db('scanwork_report_image')->insert([
                        'report_id' => $reportId,
                        'image_url' => '/uploads/baogong/' . $dateDir . '/' . $filename,
                        'createtime' => time()
                    ]);
                    return json(['code' => 1, 'msg' => '上传成功', 'data' => ['url' => '/uploads/baogong/' . $dateDir . '/' . $filename]]);
                } else {
                    return json(['code' => 0, 'msg' => '文件上传失败']);
                }
            } else {
                return json(['code' => 0, 'msg' => '文件上传错误']);
            }
        } else {
            return json(['code' => 0, 'msg' => '未接收到文件']);
        }
    }

    // 获取报工记录
    public function records(Request $request)
    {
        $openid = $request->get('openid');
        $user = db('user')->where('openid', $openid)->find();
        if (!$user) {
            return json(['code' => 0, 'msg' => '未绑定用户']);
        }
        $records = db('scanwork_report')
            ->where('user_id', $user['id'])
            ->order('createtime desc')
            ->select();
        foreach ($records as &$record) {
            $allocation = db('scanwork_allocation')->where('id', $record['allocation_id'])->find();
            if ($allocation) {
                $order = db('scanwork_order')->where('id', $allocation['order_id'])->find();
                $record['order_no'] = $order ? $order['order_no'] : '';
                $model = db('scanwork_model')->where('id', $allocation['model_id'])->find();
                $record['model_name'] = $model ? $model['name'] : '';
                if ($model) {
                    $product = db('scanwork_product')->where('id', $model['product_id'])->find();
                    $record['product_name'] = $product ? $product['name'] : '';
                } else {
                    $record['product_name'] = '';
                }
                $process = db('scanwork_process')->where('id', $allocation['process_id'])->find();
                $record['process_name'] = $process ? $process['name'] : '';
            } else {
                $record['order_no'] = '';
                $record['model_name'] = '';
                $record['product_name'] = '';
                $record['process_name'] = '';
            }
            $images = db('scanwork_report_image')
                ->where('report_id', $record['id'])
                ->field('image_url')
                ->select();
            $record['images'] = array_map(function($img) {
                return ConfigModel::getSiteDomain() . $img['image_url'];
            }, $images);
        }
        return json(['code' => 1, 'msg' => '获取成功', 'data' => $records]);
    }

    // 获取工资统计
    public function wages(Request $request)
    {
        $openid = $request->get('openid');
        $month = $request->get('month', date('Y-m'));
        $user = db('user')->where('openid', $openid)->find();
        if (!$user) {
            return json(['code' => 0, 'msg' => '未绑定用户']);
        }
        $startTime = strtotime($month . '-01 00:00:00');
        $endTime = strtotime($month . '-' . date('t', $startTime) . ' 23:59:59');
        $wages = db('scanwork_report')
            ->alias('r')
            ->join('scanwork_allocation a', 'r.allocation_id = a.id')
            ->join('scanwork_order o', 'a.order_id = o.id')
            ->join('scanwork_model m', 'a.model_id = m.id')
            ->join('scanwork_product p', 'm.product_id = p.id')
            ->join('scanwork_process pr', 'a.process_id = pr.id')
            ->where('r.user_id', $user['id'])
            ->where('r.status', 1)
            ->where('r.createtime', 'between', [$startTime, $endTime])
            ->field('r.*, o.order_no, p.name as product_name, m.name as model_name, pr.name as process_name')
            ->order('r.createtime desc')
            ->select();
        $totalWage = array_sum(array_column($wages, 'wage'));
        return json(['code' => 1, 'msg' => '获取成功', 'data' => [
            'wages' => $wages,
            'totalWage' => $totalWage,
            'month' => $month
        ]]);
    }

    // 用户信息展示
    public function userInfo(Request $request)
    {
        $openid = $request->get('openid');
        $user = db('user')->where('openid', $openid)->find();
        if (!$user) {
            return json(['code' => 0, 'msg' => '未绑定用户']);
        }
        // 可根据实际需求返回更多字段
        $info = [
            'id' => $user['id'],
            'username' => $user['username'],
            'nickname' => $user['nickname'] ?? '',
            'mobile' => $user['mobile'] ?? '',
            'avatar' => $user['avatar'] ?? '',
            'createtime' => $user['createtime'] ?? ''
        ];
        return json(['code' => 1, 'msg' => '用户信息', 'data' => $info]);
    }

    // 报工图片上传（支持多图）
    public function uploadImages(Request $request)
    {
        $openid = $request->post('openid');
        $reportId = $request->post('report_id');
        $user = db('user')->where('openid', $openid)->find();
        if (!$user) {
            return json(['code' => 0, 'msg' => '未绑定用户']);
        }
        if (!$reportId) {
            return json(['code' => 0, 'msg' => '缺少报工ID']);
        }
        $urls = [];
        if (!empty($_FILES['files'])) {
            foreach ($_FILES['files']['tmp_name'] as $idx => $tmpName) {
                if ($_FILES['files']['error'][$idx] == 0) {
                    $ext = pathinfo($_FILES['files']['name'][$idx], PATHINFO_EXTENSION);
                    $filename = date('YmdHis') . '_' . substr(md5(uniqid()), 0, 8) . '_' . $idx . '.' . $ext;
                    $dateDir = date('Y-m-d');
                    $uploadDir = 'uploads/baogong/' . $dateDir . '/';
                    if (!is_dir($uploadDir)) {
                        mkdir($uploadDir, 0755, true);
                    }
                    $filepath = $uploadDir . $filename;
                    if (move_uploaded_file($tmpName, $filepath)) {
                        db('scanwork_report_image')->insert([
                            'report_id' => $reportId,
                            'image_url' => '/uploads/baogong/' . $dateDir . '/' . $filename,
                            'createtime' => time()
                        ]);
                        $urls[] = ConfigModel::getSiteDomain() . '/uploads/baogong/' . $dateDir . '/' . $filename;
                    }
                }
            }
            if ($urls) {
                return json(['code' => 1, 'msg' => '上传成功', 'data' => ['urls' => $urls]]);
            } else {
                return json(['code' => 0, 'msg' => '文件上传失败']);
            }
        } else {
            return json(['code' => 0, 'msg' => '未接收到文件']);
        }
    }

    /**
     * 获取微信openid并自动创建微信用户
     * @ApiMethod (POST)
     * @ApiParams (name="code", type="string", required=true, description="微信登录code")
     * @ApiReturn (openid)
     */
    public function getOpenid()
    {
        $code = $this->request->post('code');
        if (!$code) {
            $this->error('缺少code参数');
        }
        $appid = ConfigModel::getMiniappAppid();
        $secret = ConfigModel::getMiniappSecret();
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid={$appid}&secret={$secret}&js_code={$code}&grant_type=authorization_code";
        $res = json_decode(file_get_contents($url), true);
        if (empty($res['openid'])) {
            $this->error('微信登录失败', null, $res);
        }
        $openid = $res['openid'];
        $user = \think\Db::name('user')->where('openid', $openid)->find();
        if (!$user) {
            // 自动创建微信用户
            $username = 'wx_' . substr($openid, -8);
            \think\Db::name('user')->insert([
                'username' => $username,
                'nickname' => '微信用户',
                'openid' => $openid,
                'createtime' => time(),
                'logintime' => time(),
                'status' => 'normal'
            ]);
        }
        $this->success('success', ['openid' => $openid]);
    }
}
